import axios from 'axios'
// import Qs from 'qs'
import router from '@/router/index'
import store from '@/store/index'
import { ElMessage } from 'element-plus'

const toLogin = () => {
    router.push({
        path: '/login',
        query: {
            redirect: router.currentRoute.fullPath
        }
    })
}
// Back pay， Run！Boss brute, four months back pay and he likes to withhold money,not recommended to stay
const api = axios.create({
    baseURL: import.meta.env.DEV ? '/proxy/' : import.meta.env.VITE_APP_API_BASEURL,
    timeout: 60000
    //   responseType: 'json'
})

api.interceptors.request.use((request) => {
    /**
     * 全局拦截请求发送前提交的参数
     * 以下代码为示例，在登录状态下，分别对 post 和 get 请求加上 token 参数
     */

    if (store.getters['user/isAuth']) {
        request.headers['A-Token'] = store.state.user.a_token
        if (store.getters['user/isLogin']) {
            request.headers['U-Token'] = store.state.user.u_token
        }
    }
    if (request.method == 'post') {
        if (request.data instanceof FormData) {
        } else {
            if (request.data == 'undefined') {
                request.data = {}
            }
        }
    } else {
        if (request.params == undefined) {
            request.params = {}
        }
    }
    return request
})

api.interceptors.response.use(
    (response) => {
        /**
         * 全局拦截请求发送后返回的数据，如果数据有报错则在这做全局的错误提示
         * 假设返回数据格式为：{ status: 1, error: '', data: '' }
         * 规则是当 status 为 1 时表示请求成功，为 0 时表示接口需要登录或者登录状态失效，需要重新登录
         * 请求出错时 error 会返回错误信息
         */

        if (response.data.code == 200) {
            return Promise.resolve(response.data)
        } else if (response.data.code == 88) {
            ElMessage({
                message: '请重新登录',
                type: 'error'
            })
            store.dispatch('user/logout').then(() => {
                router.push('/login')
            })
        } else if (response.request.responseType === 'blob') {
            return Promise.resolve(response.data)
        } else {
            let message = response.data.msg
            ElMessage({
                message,
                type: 'error'
            })

            return Promise.reject(response.data)
        }
    },
    (error) => {
        let message = error.message
        if (message == 'Network Error') {
            message = '后端网络故障'
        } else if (message.includes('timeout')) {
            message = '接口请求超时'
        } else if (message.includes('Request failed with status code')) {
            message = '接口' + message.substr(message.length - 3) + '异常'
        }
        ElMessage({
            message,
            type: 'error'
        })
        return Promise.reject(error)
    }
)

export default api
